Skip to content

Rewrite encode/decode logic to use BigInt and bitwise operators.#29

Merged
PoOwAa merged 13 commits intomainfrom
feature/bigint-bitwise-operators
May 6, 2025
Merged

Rewrite encode/decode logic to use BigInt and bitwise operators.#29
PoOwAa merged 13 commits intomainfrom
feature/bigint-bitwise-operators

Conversation

@PoOwAa
Copy link
Copy Markdown
Owner

@PoOwAa PoOwAa commented May 6, 2025

Summary by CodeRabbit

  • New Features

    • Added a performance test suite for large-scale permission operations.
    • Introduced new test cases covering edge cases and encoding variations for permission handling.
  • Refactor

    • Improved permission management logic for better efficiency using advanced bitwise operations.
    • Added validation for configuration options to ensure limits on chunk size.
  • Chores

    • Updated development dependencies to newer versions.
    • Upgraded TypeScript compiler target to ES2020.
    • Updated testing workflows to use recent Node.js versions and enhanced code coverage integration.
    • Configured test suite to exclude performance tests from regular runs.

PoOwAa added 4 commits May 6, 2025 17:39
Improves permission granting and revoking by using BigInt
operations for better performance and readability.

Simplifies encoding and decoding processes for improved efficiency.
Updates the TypeScript compilation target to ES2020, enabling the use of newer ECMAScript features.

Adds a new test case to Aclatraz.test.ts for exploring ACL code generation with a predefined set of rule IDs, allowing for more thorough testing and validation of the code generation logic.
Introduces performance tests to evaluate the efficiency of various Aclatraz operations such as code generation, permission granting, verification, and revocation.

These tests help identify potential performance bottlenecks and ensure the library scales effectively with a large number of rules.
Updates development dependencies to the latest versions.

This ensures compatibility with the newest features and
bug fixes in the tooling ecosystem.
@PoOwAa PoOwAa self-assigned this May 6, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 6, 2025

Walkthrough

The updates include major version bumps for development dependencies, a TypeScript target upgrade to ES2020, and significant internal refactoring of the Aclatraz class to use BigInt for permission management. New performance and functional tests were added, including large-scale benchmarks and a test for generating permissions with non-sequential rule IDs.

Changes

File(s) Change Summary
package.json, tsconfig.json Upgraded devDependencies to newer major versions; updated TypeScript target from ES2017 to ES2020.
src/Aclatraz.ts Refactored internal permission logic to use BigInt bitwise operations for encoding, decoding, granting, and revoking permissions; added validation for chunkSize option.
src/Aclatraz.performance.test.ts Added a new performance test suite for Aclatraz, benchmarking permission operations at large scale.
src/Aclatraz.test.ts Added a new test case for generating permissions with non-sequential rule IDs; asserts correct permission encoding and verification; added edge case and encoding coverage tests.
.github/workflows/test.yml Updated GitHub Actions Node.js versions tested from [10.x,12.x,14.x,15.x] to [22.x,23.x,24.x]; adjusted coverage step accordingly.
jest.config.ts Added testPathIgnorePatterns to exclude the new performance test file from Jest runs.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite as Test Suite
    participant Aclatraz as Aclatraz Instance

    TestSuite->>Aclatraz: addRules(rules)
    TestSuite->>Aclatraz: grantPermission(ruleIds)
    Aclatraz->>Aclatraz: Encode permissions using BigInt
    Aclatraz-->>TestSuite: permissionCode

    TestSuite->>Aclatraz: verify(permissionCode, ruleId)
    Aclatraz->>Aclatraz: Decode with BigInt, check bit
    Aclatraz-->>TestSuite: verificationResult

    TestSuite->>Aclatraz: revokePermission(permissionCode, ruleIds)
    Aclatraz->>Aclatraz: Decode with BigInt, clear bits, re-encode
    Aclatraz-->>TestSuite: updatedPermissionCode
Loading

Poem

In the warren, bits now leap with might,
BigInt paws grant and revoke with byte,
Tests race fast, a benchmark delight,
New rules hop in, both left and right.
With ES2020, we code through the night—
A rabbit’s joy: permissions done right!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3205e0e and 83d64da.

📒 Files selected for processing (1)
  • .github/workflows/test.yml (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .github/workflows/test.yml

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Updates the Node.js versions used in the test workflow to align with current supported versions. This ensures compatibility and reliable testing against the latest Node.js releases.
@PoOwAa PoOwAa requested a review from Copilot May 6, 2025 15:44
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
src/Aclatraz.performance.test.ts (4)

24-41: Enhance test with more meaningful assertions.

The performance test measures granting permissions 100,000 times but uses a trivial assertion (expect(true).toBe(true)).

  test('grantPermission 100,000 times', () => {
    const rules = [];
    for (let i = 1; i <= 100; i++) {
      rules.push({ id: i, slug: `rule${i}` });
    }
    const acl = new Aclatraz(rules);
    const ruleIds = Array.from({ length: 100 }, (_, i) => i + 1);

+   const permissionResults = [];
    const start = performance.now();
    for (let i = 0; i < 100000; i++) {
-     acl.grantPermission('', ruleIds);
+     permissionResults.push(acl.grantPermission('', ruleIds));
    }
    const end = performance.now();
    console.log(
      `grantPermission 100,000 times took: ${(end - start).toFixed(2)} ms`
    );
-   expect(true).toBe(true);
+   // Verify all permission codes are identical (deterministic)
+   expect(new Set(permissionResults).size).toBe(1);
+   // Verify the permission code is valid
+   expect(permissionResults[0].length).toBeGreaterThan(0);
  });

43-61: Improve verify test with meaningful assertions.

The performance test for verification uses a trivial assertion and doesn't validate the actual behavior.

  test('verify (decode) 100,000 times', () => {
    const rules = [];
    for (let i = 1; i <= 100; i++) {
      rules.push({ id: i, slug: `rule${i}` });
    }
    const acl = new Aclatraz(rules);
    const ruleIds = Array.from({ length: 100 }, (_, i) => i + 1);
    const permission = acl.grantPermission('', ruleIds);

+   let verifyResults = [];
    const start = performance.now();
    for (let i = 0; i < 100000; i++) {
-     acl.verify(permission, 50); // Arbitrary ruleId in the middle
+     verifyResults.push(acl.verify(permission, 50)); // Arbitrary ruleId in the middle
    }
    const end = performance.now();
    console.log(
      `verify (decode) 100,000 times took: ${(end - start).toFixed(2)} ms`
    );
-   expect(true).toBe(true);
+   // All verifications should return true since rule 50 is in the permission
+   expect(verifyResults.every(result => result === true)).toBe(true);
+   
+   // Verify that a non-existent rule returns false
+   expect(acl.verify(permission, 101)).toBe(false);
  });

63-81: Add meaningful assertions to revokePermission test.

The performance test for revoking permissions doesn't validate the actual behavior.

  test('revokePermission 100,000 times', () => {
    const rules = [];
    for (let i = 1; i <= 100; i++) {
      rules.push({ id: i, slug: `rule${i}` });
    }
    const acl = new Aclatraz(rules);
    const ruleIds = Array.from({ length: 100 }, (_, i) => i + 1);
    const permission = acl.grantPermission('', ruleIds);

+   const finalPermission = permission;
    const start = performance.now();
    for (let i = 0; i < 100000; i++) {
-     acl.revokePermission(permission, [50]); // Arbitrary ruleId
+     const result = acl.revokePermission(permission, [50]); // Arbitrary ruleId
+     if (i === 99999) finalPermission = result;
    }
    const end = performance.now();
    console.log(
      `revokePermission 100,000 times took: ${(end - start).toFixed(2)} ms`
    );
-   expect(true).toBe(true);
+   // Verify rule 50 is revoked in the final permission
+   expect(acl.verify(finalPermission, 50)).toBe(false);
+   
+   // Other rules should still be present
+   expect(acl.verify(finalPermission, 49)).toBe(true);
+   expect(acl.verify(finalPermission, 51)).toBe(true);
  });

83-144: Consider using consistent loop structures across tests.

The final three performance tests use very similar structures but slightly different approaches to iteration. For example, the verification test checks every 10,000th rule, but the others don't use sampling.

For better maintainability, consider standardizing the approach across all large-scale tests by:

  1. Using consistent sampling methods
  2. Adopting similar patterns for creating rule sets
  3. Using similar assertion patterns
src/Aclatraz.ts (3)

88-104: Avoid double ‑conversion: decode() → string → BigInt → string again

grantPermission() converts the existing permission from an encoded string
to a padded binary string (decode()), then immediately back to a BigInt
only to stringify it again when calling encode().
This causes two unnecessary string/BigInt round-trips on every call.

A lighter path is to keep the number as BigInt all the way through:

-    let aclNumber = BigInt(`0b${this.decode(currentPermission)}`);
+    // decode directly to BigInt to avoid extra conversions
+    let aclNumber = this.decodeToBigInt(currentPermission);
 ...
-    return this.encode(aclNumber.toString(2), this.options.chunkSize);
+    return this.encodeFromBigInt(aclNumber);

You already have all the building blocks inside encode()/decode(); a pair
of thin wrappers (decodeToBigInt, encodeFromBigInt) would make the core
logic faster (no string copies) and easier to read.


111-127: Symmetric improvements recommended for revokePermission()

The same conversion chain discussed above is repeated here.
Once helper methods that operate directly on BigInt exist,
revokePermission() can mirror the streamlined flow and avoid the
current overhead.


169-175: padStart may add superfluous leading zeros

After assembling the full aclNumber, you pad it to
chunkSize * chunks.length.
If the most-significant chunk is not fully utilised (very common), this
adds extra zeros that will later be re-encoded, lengthening the permission
string unnecessarily.

A safer variant is to trimStart() after padding or compute the minimal
bit-length needed.

This keeps encodings compact without losing information.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9272427 and 0887b84.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • package.json (1 hunks)
  • src/Aclatraz.performance.test.ts (1 hunks)
  • src/Aclatraz.test.ts (1 hunks)
  • src/Aclatraz.ts (4 hunks)
  • tsconfig.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/Aclatraz.test.ts (1)
src/Aclatraz.ts (1)
  • Aclatraz (6-187)
src/Aclatraz.performance.test.ts (1)
src/Aclatraz.ts (1)
  • Aclatraz (6-187)
🔇 Additional comments (4)
tsconfig.json (1)

7-7: Target upgrade enables BigInt support.

The update to ES2020 target is necessary for BigInt support, which aligns perfectly with the objective of using bitwise operators for encode/decode logic in the Aclatraz class.

src/Aclatraz.performance.test.ts (2)

1-22: Performance test properly measures code generation.

Good use of the performance API for benchmarking. This test validates generation of permission codes with 10,000 rules.


102-123: Well-structured large-scale verification test.

This test correctly measures performance for verifying permissions with 100,000 rules and includes an assertion that checks the correct number of rules were found. Good implementation.

src/Aclatraz.ts (1)

135-139: encode() – special-case for zero is correct, but loses configurability

Returning a hard-wired chunk of '0'.repeat(this.options.padding) works only
when options.encoding === 16.
If a caller changes the encoding (e.g. base-36), the zero chunk will still be
rendered in base-10 digits, breaking the round-trip with decode().

Consider delegating the zero case to the generic loop so the representation
automatically adapts to the active encoding:

-    if (aclNumber === 0n) {
-      return '0'.repeat(this.options.padding);
-    }
+    if (aclNumber === 0n) {
+      return (0n)
+        .toString(this.options.encoding)
+        .padStart(this.options.padding, this.options.paddingChar);
+    }

Comment thread src/Aclatraz.test.ts Outdated
Comment thread package.json
Comment on lines +38 to +50
"@types/jest": "^29.5.11",
"@types/node": "^20.11.30",
"@typescript-eslint/eslint-plugin": "^7.7.0",
"@typescript-eslint/parser": "^7.7.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^27.9.0",
"jest": "^29.7.0",
"np": "^8.0.4",
"rimraf": "^5.0.5",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify npm compatibility with major dependency upgrades.

The significant version bumps across all development dependencies are necessary to support ES2020 features like BigInt, but may require adjustments to CI/CD workflows or developer environments.


🏁 Script executed:

#!/bin/bash
# Check compatibility with current Node.js LTS versions
echo "Checking Node.js compatibility information"
grep -A 5 "engines" package.json || echo "No engines field specified in package.json"

# Check if any dependencies have compatibility warnings
npm ls --depth=0 || echo "Some dependencies might have compatibility issues"

Length of output: 315


🏁 Script executed:

#!/bin/bash
# Locate the package.json in the repository
fd --max-depth 2 package.json || find . -maxdepth 2 -name package.json

# Inspect for an "engines" field to lock Node.js versions
grep -R '"engines"' -n package.json || echo "No engines field in package.json"

# Check GitHub Actions workflows for Node version pins
grep -R "node-version" -n .github/workflows/ || echo "No node-version specification in workflows"

Length of output: 522


Add a Node.js engines field and update CI Node versions

To ensure developers and CI use a compatible Node.js version for these upgraded dev dependencies:

• In package.json, add an "engines" section (e.g. "node": ">=16") to lock the minimum Node.js version.
• In .github/workflows/test.yml, bump the node-version matrix to current LTS releases (e.g. 16.x, 18.x, 20.x), replacing the old 10.x, 12.x, 14.x, 15.x entries.
• Verify local environments are running Node.js ≥16 before installing.

These changes will align your CI/CD and developer machines with the requirements of TypeScript 5.4+, ESLint 8.x, and other modern tooling.

Comment thread src/Aclatraz.ts
Comment thread src/Aclatraz.ts
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR rewrites the encode/decode logic to use BigInt and bitwise operators for improved efficiency and adds performance tests for large-scale permission operations. Key changes include:

  • Replacing array-based binary manipulation with BigInt bitwise operations in grantPermission, revokePermission, encode, and decode.
  • Enhancing tests with additional cases and performance benchmarks for different permission operations.
  • Updating the CI workflow to use newer Node.js versions.

Reviewed Changes

Copilot reviewed 6 out of 7 changed files in this pull request and generated 1 comment.

File Description
src/Aclatraz.ts Rewritten encode/decode logic using BigInt and bitwise manipulations.
src/Aclatraz.test.ts Added new test cases and updated existing tests.
src/Aclatraz.performance.test.ts Introduced performance tests for permission operations.
.github/workflows/test.yml Updated Node.js versions for continuous integration.
Files not reviewed (1)
  • package.json: Language not supported

Comment thread src/Aclatraz.ts Outdated
PoOwAa and others added 8 commits May 6, 2025 17:48
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Adds a comprehensive integration test to verify the encoding and decoding of a set of rules within Aclatraz.

This test ensures that adding, encoding, and verifying a collection of rule IDs functions correctly, increasing confidence in the overall reliability of the Aclatraz system.
Specifies the minimum Node.js version required to run the package, ensuring compatibility and preventing potential issues with older Node.js versions.
Adds validation to ensure the `chunkSize` option
does not exceed 128, preventing potential issues
with large chunk sizes.

Updates option setting logic to include the new validation.
Enables the library to handle ACL chunks encoded in formats other than hexadecimal, providing more flexibility in processing ACL data.
Adds tests to cover edge cases, specifically constructor
chunk size validation and non-hex encoding support.

This improves code robustness and test coverage.
Adds tests and implementations to better handle different encoding options,
chunk sizes, and padding configurations. This increases the flexibility and
robustness of Aclatraz permission management.

Also prevents `chunkSize` from being set to a value larger than 128 to avoid
unexpected behavior.
Updates the code coverage action to the latest version.
This ensures compatibility with newer environments and
potentially includes performance improvements and bug fixes.

Adds CODECOV_TOKEN environment variable.
@codecov-commenter
Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (9272427) to head (83d64da).

Additional details and impacted files
@@            Coverage Diff            @@
##              main       #29   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            2         2           
  Lines           90       119   +29     
  Branches        13        25   +12     
=========================================
+ Hits            90       119   +29     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@PoOwAa PoOwAa merged commit fc70e39 into main May 6, 2025
4 checks passed
@PoOwAa PoOwAa deleted the feature/bigint-bitwise-operators branch May 6, 2025 16:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants